package com.SFA.OrderManagement;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

import com.FrameWork.Common.AbstractBaseActivity;
import com.FrameWork.Common.BuilderView;
import com.FrameWork.Common.CommonFunction;
import com.FrameWork.Entity.CustomerInfoEntity;
import com.FrameWork.Entity.DataEntity;
import com.FrameWork.Entity.ProductEntity;
import com.SFA.R;
import com.SFA.OrderManagement.HorizationalProductAdapter.ISelectProduct;


public class SelectProductActivity extends AbstractBaseActivity implements OnQueryTextListener,ActionBar.TabListener,OnClickListener, ISelectProduct {
	List<DataEntity> brandList;
	private CustomerInfoEntity entity;
	public List<ProductEntity> selectedList = new ArrayList<ProductEntity>();
	private LinearLayout layoutForms;
	private boolean isNewOrder= false;
	private MenuItem shoppingcart = null;
	private AuditCPRManager manager;;
	private ProductListAdapter adapter;
	private ListView listView;
	private GridView listAllProduct;
	private HorizationalProductAdapter adapterProduct;
	private List<ProductEntity> productList;
	SearchView searchView;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if(isNewOrder)
			{

			}
			else
			{
				Return();
			}
		}
		return super.onKeyDown(keyCode, event);
	}


	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.selectproduct);
		this.setTitle("选择产品");
		listView =(ListView) findViewById(R.id.listProduct);
		layoutForms = (LinearLayout)findViewById(R.id.layoutForms);
		listAllProduct= (GridView)findViewById(R.id.listAllProduct);
		ActionBar bar = getActionBar();


		if(savedInstanceState != null)
		{
			entity = (CustomerInfoEntity)savedInstanceState.getSerializable("CUSTOMER");

			selectedList =  (List<ProductEntity>)savedInstanceState.getSerializable("DATA");
		}
		else
		{

			entity = (CustomerInfoEntity)this.getIntent().getSerializableExtra("CUSTOMER");
			selectedList =  (List<ProductEntity>)this.getIntent().getSerializableExtra("DATA");
			isNewOrder="NEW".equals(getIntent().getStringExtra("SOURCE"));


		}
		if(selectedList == null)
		{
			selectedList= new ArrayList<ProductEntity>();
		}
		manager =  new AuditCPRManager(context,entity);
		//查找品牌,横向是所有的品牌
		brandList = manager.getDataEntityList(false,2);
		for (DataEntity entity : brandList) {
			Tab tab = bar.newTab().setText(entity.NAME)
					.setTabListener(this);
			tab.setTag(entity);
			bar.addTab(tab);
		}

		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		MenuItem item = menu.findItem(R.id.search);
		searchView= (SearchView) item.getActionView();
		searchView.setOnQueryTextListener(this);
		searchView.setActivated(true);
		//显示购物车菜单项
		if(isNewOrder)
			shoppingcart = menu.add(item.getGroupId(), 100,item.getOrder(), "提交到购物车");
		return true;
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {

	}
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		//选中一个品牌以后

		List<DataEntity> formList = manager.getFormList(((DataEntity)tab.getTag()).CODE);
		layoutForms.removeAllViews();
		if(formList.size()>0)
		{
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
			params.weight=1;
			//显示系列选项卡
			for (int i = 0; i < formList.size(); i++)
			{
				BuilderView view = new BuilderView(this);
				view.setTitle(formList.get(i).NAME);
				view.setTag(formList.get(i));
				view.setOnClickListener(this);
				layoutForms.addView(view, params);
			}
			this.onClick(layoutForms.getChildAt(0));
		}
		else if(adapterProduct != null)
		{
			listAllProduct.setAdapter(null);
		}
		listView.setVisibility(View.GONE);
	}
	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {

	}




	private DataEntity CurrentFormEntity;


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(isNewOrder)
		{
			if(item == this.shoppingcart)
			{
				if(selectedList == null || selectedList.size() ==0)
				{
					CommonFunction.ShowDialog(context, "请选择需要订购的商品，谢谢！");

				}
				else
				{
					ClearPool();
					Intent intent = new Intent(this, OrderDetailActivity.class);
					intent.putExtra("CUSTOMER", entity);
					intent.putExtra("DATA", (Serializable)selectedList);
					startActivity(intent);
					finish();
					overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);  
				}
			}
		}
		else if(item.getItemId() == android.R.id.home)
		{
			Return();
		}


		return false;
	}

	private void ClearPool()
	{
		//HorizationalProductAdapter.pool.shutdownNow();

		if(adapterProduct != null)
		{
			for(int index=0;index<listAllProduct.getChildCount();index++)
			{
				HorizationalProductAdapter.ViewHolder holder = (HorizationalProductAdapter.ViewHolder)listAllProduct.getChildAt(index).getTag();
				if(holder.future != null && !holder.future.isDone())
					holder.future.cancel(true);
			
			}
		}
	}
	private void Return()
	{
		ClearPool();
		Intent intent = new Intent();
		intent.putExtra("DATA", (Serializable)selectedList);
		this.setResult(100, intent); 
		finish(); 
		System.gc();
	}
	@Override
	public void onClick(final View v)
	{
		//选中一个系列的时候触发
		if(v instanceof  BuilderView )
		{
			for (int i = 0; i < layoutForms.getChildCount(); i++) 
			{
				if (layoutForms.getChildAt(i) == v) {
					listView.setVisibility(View.GONE);
					v.setSelected(true);
					//刷新产品列表
					CurrentFormEntity = (DataEntity) v.getTag();
					//刷新产品列表
					productList=manager.getDataEntityByForm(CurrentFormEntity.CODE);
					for(int index=0;index<productList.size();index++)
					{

						for(ProductEntity selected: selectedList)
						{
							if(selected.ID.equals(productList.get(index).ID))
								productList.get(index).Checked =true;
						}

					}
					ClearPool();
					adapterProduct = new HorizationalProductAdapter(context,productList);
					adapterProduct.OnSelectProduct = this;
					listAllProduct.setAdapter(adapterProduct);
				}
				else
				{
					layoutForms.getChildAt(i).setSelected(false);
				}
			}
		}

	}
	@Override
	public void Select(ProductEntity entity) {
		if(entity == null)
			return;
		if(entity.Checked)
		{
			for(ProductEntity prod : selectedList)
			{
				if(prod.ID.equals(entity.ID))
					return;
			}
			selectedList.add(entity);
		}
		else
		{
			for(ProductEntity prod : selectedList)
			{
				if(prod.ID.equals(entity.ID))
				{
					selectedList.remove(prod);
					break;
				}
			}

		}
		//设置购物车的数量
		if(isNewOrder)
			shoppingcart.setTitle("购物车(" + selectedList.size() + ")");
	}

	@Override
	public boolean onQueryTextChange(String query) {
		BindProduct(query);
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		//查找满足条件的产品
		BindProduct(query);
		return false;
	}

	private void BindProduct(String key)
	{
		if(TextUtils.isEmpty(key))
		{
			listView.setVisibility(View.GONE);
		}
		else
		{
			List<ProductEntity> list = manager.QueryProduct(key);
			
			adapter = new ProductListAdapter(list,context);
			adapter.ShowPicture(true);
			OnItemClickListener listener = new OnItemClickListener()
			{

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					ProductEntity entity = 	adapter.getItem(arg2);
					//判断是否存在
					boolean exist = false;
					for(ProductEntity prod : selectedList)
					{
						if(prod.ID.equals(entity.ID))
						{
							exist = true;
							break;
						}
					}
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
					imm.hideSoftInputFromWindow(searchView.getWindowToken(),0);
					if(!exist)
					{
						selectedList.add(entity);
						//设置购物车的数量
						if(isNewOrder)
							shoppingcart.setTitle("购物车(" +  selectedList.size() + ")");
					}
					listView.setVisibility(View.GONE);


				}

			};
			listView.setOnItemClickListener(listener );
			listView.setVisibility(View.VISIBLE);
			listView.setAdapter(adapter);

		}
	}
}
